package com.program.config;

import java.io.Serializable;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CustomSessionManager extends DefaultWebSessionManager {

    private static final Logger log = LoggerFactory.getLogger(CustomSessionManager.class);

    private static final String Authorization = "Authorization";

    public CustomSessionManager() {
        super();
        // 使用默认值30分钟
//		setGlobalSessionTimeout(5*MILLIS_PER_MINUTE);
//		setGlobalSessionTimeout(DEFAULT_GLOBAL_SESSION_TIMEOUT);

    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {

        // 如果请求头中有 Authorization 则其值为sessionId，该配置为了解决前后端分离的跨域请求，使用tokenId验证
        String sessionId = WebUtils.toHttp(request).getHeader(Authorization);
        if (!StringUtils.isEmpty(sessionId)) {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
                    ShiroHttpServletRequest.COOKIE_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);

            return sessionId;
        } else {
            return super.getSessionId(request, response);
        }
    }
}
